package com.cipe.cmrs.service;

import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Map;

import org.springframework.stereotype.Service;

import com.cipe.cmrs.model.ChangeNotificationsMessage;
import com.cipe.cmrs.model.User;
import com.cipe.cmrs.model.UserPreference;
import com.cipe.cmrs.model.Useractionalertschanges;
import com.cipe.cmrs.util.Util;

/**
 * @author krishna The service class to Change Notification message message
 */
@Service
public class ChangeNotificationMessageService extends
		BaseService<ChangeNotificationsMessage> {
	/**
	 * We are taking child object, as EntityManager won't support Hibernate
	 * Filter concept. This method is not going to use .
	 * 
	 * @param user
	 * @return
	 */
	public String getnotIncondition(User user) {
		StringBuilder ids = new StringBuilder("99999999");
		for (Useractionalertschanges useractionalertschanges : user
				.getUseractionalertschangesList())
			ids.append("," + useractionalertschanges.getChnagenotificationid());
		return ids.toString();
	}

	/**
	 * This method is also use less for the application now as the 4th method
	 * can behave dynamically.
	 * 
	 * @param user
	 * @return
	 */
	public List<ChangeNotificationsMessage> getAllChangeNotification(User user) {
		return this.dao
				.getResultList("select o from ChangeNotificationsMessage o where o.id not in("
						+ getnotIncondition(user) + ")");
	}

	public void chnageNotificationPeference(User user, int id) {
		Useractionalertschanges useractionalertschanges = new Useractionalertschanges();
		useractionalertschanges.setChnagenotificationid(id);
		useractionalertschanges
				.setDateread(new Timestamp(new Date().getTime()));
		useractionalertschanges.setUser(user);
		user.getUseractionalertschangesList().add(useractionalertschanges);
	}

	/**
	 * if the changeNotification content null value then it will return all the
	 * notifications
	 * 
	 * @author Krishna
	 * @param changeNotification
	 * @param user
	 * @return
	 */
	public List<ChangeNotificationsMessage> getAllChangeNotification(
			UserPreference userPreference, User user) {
	    List<ChangeNotificationsMessage> changeNotificationsMessages = new ArrayList<ChangeNotificationsMessage>();
		String datecondition = "";
		Calendar calendar = Calendar.getInstance();

		Timestamp timestamp = new Timestamp(new Date().getTime());
		if (userPreference.getCnDateid() != null) {
			if (2 == userPreference.getCnDateid()) {
				calendar.set(Calendar.HOUR_OF_DAY, 0);
				calendar.set(Calendar.HOUR_OF_DAY, 0);
				calendar.set(Calendar.MINUTE, 0);
				calendar.set(Calendar.SECOND, 0);
				calendar.set(Calendar.MILLISECOND, 0);
				datecondition = Util.createRangeQueryClause("c.date",
						new Timestamp(calendar.getTimeInMillis()), timestamp);

			} else if (3 == userPreference.getCnDateid()) {
				calendar.add(Calendar.DATE, -7);
				datecondition = Util.createRangeQueryClause("c.date",
						new Timestamp(calendar.getTimeInMillis()), timestamp);
			} else if (4 == userPreference.getCnDateid()) {
				calendar.add(Calendar.DATE, -30);
				datecondition = Util.createRangeQueryClause("c.date",
						new Timestamp(calendar.getTimeInMillis()), timestamp);
			}
		}
		
        StringBuilder filterTypeCondition = new StringBuilder();
        if (userPreference.getCnid() != null && userPreference.getCnid() > 0) {
            filterTypeCondition.append(Util.createQueryClause("c.changenotification.id", userPreference.getCnid()));
        } else {
            Map<String, Map<String, String>> allowedUiElementsMap = user.getAllowedUiElementsMap();
            // TODO: Need "Change Notifications" key into constants or property file
            Map<String, String> allowedNotifications = allowedUiElementsMap.get("Change Notifications");
            if (allowedNotifications != null && allowedNotifications.size() > 0) {
                List<String> notificationTypes = new ArrayList<String>(allowedNotifications.keySet());
                int i = 0;
                filterTypeCondition.append(" AND (");
                for (; i < notificationTypes.size() - 1; i++) {
                    filterTypeCondition.append("c.changenotification.type = '" + notificationTypes.get(i) + "' OR ");
                }
                filterTypeCondition.append("c.changenotification.type = '" + notificationTypes.get(i) + "')");
            }
        }
        
        if(filterTypeCondition.length() > 0) {
    		String userCondition="";
    		if(userPreference.getCnAsignId() !=null){
    			userCondition=" and ( c.programOfficer="+userPreference.getCnAsignId()+" or c.regionaldirector="+userPreference.getCnAsignId()
    			+" or c.programAssistant="+userPreference.getCnAsignId()+")";
    		}
    		
    		String query = "SELECT c FROM ChangeNotificationsMessage c where  c.id not in("
    				+ getnotIncondition(user)
    				+ ") and c.changenotification.id != 2"
    				+ filterTypeCondition.toString()
    				+ datecondition+userCondition+
    				Util.createQueryClause("c.region", userPreference.getCnReagionId())
    				+ Util.createOrderByDesc("c.date");
    
    		changeNotificationsMessages=this.dao.getResultList(query);
    		/**
    		 * For payment request no region comparision
    		 */
    		query = "SELECT c FROM ChangeNotificationsMessage c where  c.id not in("
    			+ getnotIncondition(user)
    			+ ") and c.changenotification.id = 2"
    			+ filterTypeCondition.toString()
    			+ datecondition+userCondition
    			+ Util.createOrderByDesc("c.date");
    		
    		changeNotificationsMessages.addAll(this.dao.getResultList(query));
        }
		return changeNotificationsMessages;
	}
	 
}
